﻿'use strict';

// todoPage controller
app.controller('saleWarehousing', ['$stateParams','$state','$filter','$window','$http','$scope','$modal','toaster','$log', function($stateParams,$state,$filter,$window,$http,$scope,$modal,toaster,$log) {
    function inIt(){
        if($stateParams.docId===null){
            getList();
        }else if($stateParams.docId==="new"){
            $scope.warehouseJump();
        }else{
            toaster.getInfo('/a_yongan/single/salesout/'+$stateParams.docId,null).then(function(data){
                if(data && data.data && data.data.data){
                    makeData([data.data.data],true);
                }
            });

        }
    }
    $scope.canEdit = false;
    $scope.goods=[];//定义数组
    $scope.lists = [""];
    $scope.mylabel = $scope.lists[0];//默认数组第一个作为option的值
    function getSelect(){
        toaster.getInfo('/a_yongan/selectlist/warehouse',null).then(function(data){
            if(data && data.data && data.data.data){
                data.data.data.forEach(function(item){
                    $scope.lists.push(item.name);
                });
            }
        });
    }
    getSelect();
    //删除一行
    $scope.dele =function($index){
        $scope.goods.splice($index,1);
    };
    //添加的方法
    $scope.addRows=function(){
        var id = new Date().getTime();
        var go = {
            "flag":false,
            "salesOrderDetailsId":id,
            "salesOrderDetailsHpbm":"",
            "salesOrderDetailsHpmc":"",
            "salesOrderDetailsGgxh":"",
            "salesOrderDetailsHpdw":"",
            "salesOrderDetailsHpddsl":"",
            "salesOrderDetailsHpsl":"",
            "salesOrderDetailsHpdj":"",
            "salesOrderDetailsHpzje":"",
            "salesOrderDetailsDhrq":"",
            "salesOrderDetailsBz":""
        }
        $scope.goods.push(go);
    };
    function objToGo(obj,index){
        $scope.goods[index].salesOrderDetailsHpbm=obj.id;
        $scope.goods[index].salesOrderDetailsHpmc=obj.name;
        $scope.goods[index].salesOrderDetailsGgxh=obj.hpxh;
        $scope.goods[index].salesOrderDetailsHpdw=obj.dw;
        $scope.goods[index].salesOrderDetailsHpdj=obj.dj;
        $scope.goods[index].salesOrderDetailsHpzje=parseInt($("#"+$scope.goods[index].salesOrderDetailsId+"salesOrderDetailsHpsl").val())*parseFloat(obj.dj);
    }
    $scope.detailsInput = {
        sl:function(index){
            var sl = $("#"+$scope.goods[index].salesOrderDetailsId+"salesOrderDetailsHpsl").val();
            var dj = $scope.goods[index].salesOrderDetailsHpdj;
            $scope.goods[index].salesOrderDetailsHpsl = sl;
            if(dj===""){
                showMessage('warning','',"货品信息不能为空！");
                return false;
            }
            $scope.goods[index].salesOrderDetailsHpzje = parseFloat(dj)*parseInt(sl);
        },
        bz:function(index){
            $scope.goods[index].salesOrderDetailsBz = $("#"+$scope.goods[index].salesOrderDetailsId+"salesOrderDetailsBz").val();
        }
    };
    //改变每行chekbox的状态
    $scope.ck = function($index){
        $scope.goods[$index].flag=!$scope.goods[$index].flag
    }
    //批量删除
    $scope.plsc = function(){
    //反着遍历
        for (var i = $scope.goods.length-1;i>=0;i--) {
            if ($scope.goods[i].flag) {
                $scope.goods.splice(i,1);
            }
        }
    }
    //全选
    var qq = true;
    $scope.qx = function(){
    //获取属性
        var ck = $("input[name=ck]")
        for (var i=0;i<ck.length;i++) {
            ck[i].checked=qq;
            //给每个数组中的ck赋值
            $scope.goods[i].flag=qq;
        }
        qq=!qq;
    };
    $scope.chooseGood = function(){
        alert('弹出选择框');
    }
    $scope.title = {
        title:'销售出库单列表',
        addTitle:'销售出库单信息'
    };
    $scope.toaster = {
        type: 'warning',
        title: '提示：',
        text: '内容不能为空！'
    };
    $scope.heji = {"ddje":0,"jehj":0,"sl":0};
    function makeData(data,single){
        $scope.heji = {"ddje":0,"jehj":0,"sl":0};
        data.forEach(function (item) {
            item.createTime = $filter("date")(item.createTime, "yyyy/MM/dd");
            item.zje = 0;
            item.zsl = 0;
            item.details.forEach(function(detail){
                detail.salesOrderDetailsDhrq = $filter("date")(detail.salesOrderDetailsDhrq, "yyyy/MM/dd");
                item.zje = item.zje + parseFloat(detail.salesOrderDetailsHpzje);
                item.zsl = item.zsl + parseFloat(detail.salesOrderDetailsHpsl);
            });
            $scope.heji.ddje = $scope.heji.ddje + parseFloat(item.showZje);
            $scope.heji.jehj = $scope.heji.jehj + item.zje;
            $scope.heji.sl = $scope.heji.sl + item.zsl;
            if(item.state.indexOf("办结")>=0){
                item.status1 = 'label bg-danger';
            }else{
                item.status1 = 'label bg-info';
            }
        })
        if(single){
            $scope.showInfo(data[0]);
        }else{
            $scope.saveDate = data;
        }
    }
    function getList(){
        toaster.getInfo('/a_yongan/list/salesout',null).then(function(data){
            if(data && data.data && data.data.data){
                makeData(data.data.data);
            }
        });
    }
    $scope.pop = function(){
        toaster.pop($scope.toaster.type, $scope.toaster.title, $scope.toaster.text);
    };
    function showMessage(type,title,text){
        $scope.toaster.type = type;
        $scope.toaster.text = text;
        toaster.pop($scope.toaster.type, $scope.toaster.title, $scope.toaster.text);
    }
    function checkItems(){
        var items = ['salesOutGmkh'];
        var itemsValue = ['客户'];
        for(var i=0;i<items.length;i++){
            if($('#'+items[i]+'').val()===''){
                $('#'+items[i]+'').focus();
                showMessage('warning','',itemsValue[i]+"不能为空！");
                return false;
            }
        }
        return true;
    }
    $scope.message = '';
    $scope.saveInfo = function (size,msg) {
        var type='';
        if(msg==='th'){
            type = '退回';
        }else if(msg==='bc'){
            type = '保存';
        }else if(msg==='tj'){
            type ='提交';
        }else{
            return;
        }
        $scope.message = '是否确定'+type+'？';
        if(!checkItems()){
            return;
        }
        var modalInstance = $modal.open({
            templateUrl: 'myModalContent.html',
            controller: 'ModalInstanceCtrl',
            size: size,
            resolve: {
                items: function () {
                    return $scope.message;
                }
            }
        });
        modalInstance.result.then(function (selectedItem) {
            var info = addDo(msg);
        }, function () {
            $log.info('Modal dismissed at: ' + new Date());
        });
    };
    $scope.showOrderInfo = function(){
        var dataItem = {
            "order":null,
            "info":null
        };
        if($scope.row.salesOutXsdh!=="" && $scope.row.salesOutXsdh){
            toaster.getInfo('/a_yongan/list/salesdetail/'+$scope.row.salesOutXsdh,null).then(function(data){
                if(data && data.data && data.data.data){
                    dataItem.order = data.data.data;
                    toaster.getInfo('/a_yongan/list/salesoutbyorder/'+$scope.row.salesOutXsdh,null).then(function(data){
                        if(data && data.data && data.data.data){
                            dataItem.info = data.data.data;
                            var modalInstance = $modal.open({
                                templateUrl: 'showSalesInfo.html',
                                controller: 'showSalesInfoCtrl',
                                size: 'lg',
                                resolve: {
                                    items: function () {
                                        return dataItem;
                                    }
                                }
                            });
                        }else{
                            showMessage('warning','',"没有出库信息！");
                            return;
                        }
                    });
                }else{
                    showMessage('warning','',"没有订货单信息！");
                }
            });

        }else{
            showMessage('warning','',"订单编号为空！");
            return;
        }
    };
    $scope.isshow=true;
    $scope.warehouseAdd = false;
    $scope.warehouseList = true;
    $scope.warehouseJump = function(ts) {
        if(ts!=='back'){
            $scope.canEdit = true;
            $scope.mylabel = $scope.lists[0];
            $scope.row = {};
            $scope.showFiles = [];
            $scope.goods = [];
            $scope.row = {
                'createTime':$filter("date")(new Date(), "yyyy/MM/dd"),
                'zdr':$scope.app.userName,
                'upDateUserId':"new",
                'salesOutCkje':"0",
                'salesOutCkdh':'XSCK'+$filter("date")(new Date(), "yyyyMMddHHmmss")
            };
        }else{
            $scope.canEdit = false;
            getList();
        }
        $scope.warehouseAdd = !($scope.warehouseAdd);
        $scope.warehouseList = !($scope.warehouseList);
    };
    $scope.row = {};
    $scope.columns = [
        {
            title:'创建时间',
            show:true
        },
        {
            title:'出库单号',
            show:true
        },
        {
            title:'客户',
            show:true
        },
        {
            title:'订单编号',
            show:true
        },
        {
            title:'发货仓库',
            show:true
        },
        {
            title:'文件状态',
            show:true
        },
        {
            title:'入库总金额',
            show:true
        },
        {
            title:'货品名称',
            show:true
        },
        {
            title:'金额合计',
            show:true
        },
        {
            title:'数量合计',
            show:true
        },
        {
            title:'操作',
            show:true
        }
    ];

    $scope.saveDate=[];
    $scope.showInfo = function(row){
        $scope.row = row;
        $scope.goods = row.details;
        $scope.showFlowDetailsShow = false;
        $scope.showFlowDetailsData = [];
        //判断有没有编辑的权限
        if($scope.row.salesOutId && $scope.row.salesOutId!==""){
            toaster.getInfo('/a_yongan/single/editpower/'+$scope.row.salesOutId,null).then(function(data){
                if(data && data.data){
                    $scope.canEdit = data.data.success;
                }
            });
        }
        $scope.warehouseAdd = !($scope.warehouseAdd);
        $scope.warehouseList = !($scope.warehouseList);
        var isHave = false;
        $scope.lists.forEach(function(item){
            if(item === $scope.row.salesOutFhck){
                isHave = true;
            }
        });
        if(!isHave){
            $scope.lists.push($scope.row.salesOutFhck);
        }
        $scope.mylabel = $scope.row.salesOutFhck;
        getAllFile();
    };
    $scope.showSelectCustomer = function(name,lxr,ph){
        var modalInstance = $modal.open({
            templateUrl: 'selectCustomer.html',
            controller: 'selectCustomerCtrl',
            size: 'sm',
            resolve: {
                items: function () {
                    return $scope.message;
                }
            }
        });
        modalInstance.result.then(function (selectedItem) {
            $('#'+name+'').val(selectedItem.name);
            $('#'+lxr+'').val(selectedItem.people);
            $('#'+ph+'').val(selectedItem.phone);
            showMessage('success','','选择成功！');
            //$scope.selected = selectedItem;
        }, function () {
            $log.info('Modal dismissed at: ' + new Date());
        });
    };
    $scope.showSelectOrder = function(){
        var modalInstance = $modal.open({
            templateUrl: 'selectSaleOrder.html',
            controller: 'selectSaleOrderCtrl',
            size: 'lg',
            resolve: {
                items: function () {
                    return $("#salesOutGmkh").val();
                }
            }
        });
        modalInstance.result.then(function (selectedItem) {
            $scope.goods = selectedItem.details;
            $scope.goods.forEach(function(item){
                item.salesOrderDetailsHpddsl=item.salesOrderDetailsHpsl;
                item.salesOrderDetailsHpsl = 0;
                item.salesOrderDetailsHpzje = 0;
            });
            $scope.row.salesOutXsdh = selectedItem.salesOrderXsdh;
            $scope.row.salesOutGmkh = selectedItem.salesOrderGmkh;
            $scope.row.salesOutDhr = selectedItem.salesOrderDhr;
            $scope.row.salesOutLxdh = selectedItem.salesOrderLxdh;
            $scope.row.salesOutFhck = selectedItem.salesOrderXsck;
            $scope.lists.push(selectedItem.salesOrderXsck);
            $scope.mylabel = selectedItem.salesOrderXsck;
            showMessage('success','','选择成功！');
            //$scope.selected = selectedItem;
        }, function () {
            $log.info('Modal dismissed at: ' + new Date());
        });
    };
    $scope.SelectPrice = function(index,bm){
        if(bm.salesOrderDetailsHpbm && bm.salesOrderDetailsHpbm!==""){
            toaster.getInfo('/a_yongan/list/goodsprice/'+bm.salesOrderDetailsHpbm,null).then(function(data){
                if(data && data.data && data.data.data){
                    console.log(data.data.data);
                    var modalInstance = $modal.open({
                        templateUrl: 'selectPrice.html',
                        controller: 'selectPriceCtrl',
                        size: 'sm',
                        resolve: {
                            items: function () {
                                return data.data.data;
                            }
                        }
                    });
                    modalInstance.result.then(function (selectedItem) {
                        $scope.goods[index].salesOrderDetailsHpdj = selectedItem;
                        $scope.goods[index].salesOrderDetailsHpzje = parseFloat(selectedItem)*parseFloat($scope.goods[index].salesOrderDetailsHpsl);
                        showMessage('success','','选择成功！');
                    }, function () {
                        $log.info('Modal dismissed at: ' + new Date());
                    });
                }
            });
        }else{
            showMessage('warning','','货品编码不能为空！');
        }
    };
    function addDo(type){
        var notesdata = {};
        if($scope.canEdit){
            $scope.goods.forEach(function(item){
                item.salesOrderDetailsDhrq=new Date($("#"+item.salesOrderDetailsId+"salesOrderDetailsDhrq").val()).getTime();
            });
            if(!$scope.row.salesOutId){
                notesdata = {
                    "salesOutId":"",
                    //"qy":$("#qy").prop("checked"),
                    "zdr":$scope.app.userName,
                    "zdrId":$scope.app.userId,
                    "salesOutCkdh":$("#salesOutCkdh").val(),
                    "salesOutGmkh":$("#salesOutGmkh").val(),
                    "salesOutDhr":$("#salesOutDhr").val(),
                    "salesOutLxdh":$("#salesOutLxdh").val(),
                    "salesOutXsdh":$("#salesOutXsdh").val(),
                    "salesOutFhck":$scope.lists[$("#salesOutFhck").val()],
                    "salesOutCkje":$("#salesOutCkje").val(),
                    "salesOutBz":$("#salesOutBz").val(),
                    "details":$scope.goods
                }
            }else{
                notesdata = {
                    "salesOutId":$scope.row.salesOutId,
                    //"qy":$("#qy").prop("checked"),
                    "salesOutCkdh":$("#salesOutCkdh").val(),
                    "salesOutGmkh":$("#salesOutGmkh").val(),
                    "salesOutDhr":$("#salesOutDhr").val(),
                    "salesOutLxdh":$("#salesOutLxdh").val(),
                    "salesOutXsdh":$("#salesOutXsdh").val(),
                    "salesOutFhck":$scope.lists[$("#salesOutFhck").val()],
                    "salesOutCkje":$("#salesOutCkje").val(),
                    "salesOutBz":$("#salesOutBz").val(),
                    "details":$scope.goods
                }
            }
        }else{
            $scope.goods.forEach(function(item){
                item.salesOrderDetailsDhrq=new Date(item.salesOrderDetailsDhrq).getTime();
            });
            $scope.row.createTime = new Date($scope.row.createTime).getTime();
            notesdata = $scope.row;
        }

        var info="";
        toaster.postInfo('/a_yongan/add/salesout',notesdata).then(function(data){
            if(data && data.data && data.data.success && data.data.data){
                if(type!=='bc'){
                    var params = {
                        "id":data.data.data.personalWorkDocId,
                        "type":1,
                        "flow":"salesout",
                        "data":data.data.data
                    };
                    if(type==="th"){
                        params.type = -1;
                    }
                    toaster.postInfo('/a_yongan/workflow/salesout',params).then(function(data){
                        if(data &&  data.data && data.data.success){
                            showMessage('seccess','','操作成功！');
                            if($scope.app.power.powerSaleWarehousing){
                                $scope.warehouseAdd = !($scope.warehouseAdd);
                                $scope.warehouseList = !($scope.warehouseList);
                                getList();
                            }else{
                                alert('提交成功，即将返回待办界面！');
                                $state.go('app.todoPage');
                            }
                            return info;
                        }else{
                            showMessage('warning','','操作失败！');
                            info = "请求错误！";
                        }
                    });
                }else{
                    showMessage('seccess','','保存成功！');
                    $scope.warehouseAdd = !($scope.warehouseAdd);
                    $scope.warehouseList = !($scope.warehouseList);
                    getList();
                    return info;
                }
                //return info;
            }else{
                showMessage('warning','','保存失败！');
                info = "请求错误！";
            }
        });
        return info;
    }

    $scope.showSelectGoods = function(obj,index,searchHpmc){
        var modalInstance = $modal.open({
            templateUrl: 'selectGoods.html',
            controller: 'selectGoodsCtrl',
            size: 'sm',
            resolve: {
                items: function () {
                    return $scope.message;
                }
            }
        });
        modalInstance.result.then(function (selectedItem) {
            if(obj===null && index===null){
                $("#"+searchHpmc).val(selectedItem.name);
                $("#"+searchHpmc+"Id").val(selectedItem.id);
            }else{
                objToGo(selectedItem,index);
            }
            showMessage('success','','选择成功！');
            //$scope.selected = selectedItem;
        }, function () {
            $log.info('Modal dismissed at: ' + new Date());
        });
    };
    $scope.showFiles = [];
    $scope.upFile=function(){
        var obj = $("#uploadFile")[0];
        var isHaveFile = false;
        $scope.showFiles.forEach(function(item){
            if(item.myFileRealName===obj.files[0].name){
                isHaveFile = true;
            }
        });
        if(isHaveFile){
            showMessage('warning','',"已存在同名文件或重复文件！");
            return false;
        }
        $scope.showFiles.push({
            myFileRealName:obj.files[0].name,
            myFileSize:obj.files[0].size,
            isSuccess:false,
            isCancel:false,
            isError:false,
            isUploading:false,
            progress:0,
            file:obj.files[0]
        });
    };
    $scope.doupFile=function(index){
        uploadFiles(index);
    };

    function makeFileData(data){
        data.forEach(function(item){
            item.progress = 100;
            item.isSuccess = true;
            item.isCancel = true;
            item.isError = false;
            item.isUploading = true;
        });
        $scope.showFiles = data;
    }
    function getAllFile(){
        toaster.getInfo('/a_yongan/file/getallfile/'+$scope.row.salesOutCkdh,null).then(function(data){
            if(data && data.data && data.data.success){
                makeFileData(data.data.data);
            }
        });
    }
    $scope.deleteFile = function (index) {
        if(!$scope.showFiles[index].isUploading){
            $scope.showFiles.splice(index,1);
        }else{
            toaster.getInfo('/a_yongan/file/deletefile/'+$scope.showFiles[index].myFileId,null).then(function(data){
                if(data && data.data && data.data.success){
                    $scope.showFiles.splice(index,1);
                    showMessage('success','','删除成功！');
                }else{
                    showMessage('warning','','删除失败！');
                }
            });
        }
    };
    function uploadFiles(index){
        $scope.showFiles[index].isUploading = true;
        var formData = new FormData();
        //formData.append("file",$("#uploadFile")[0].files[0]);//append()里面的第一个参数file对应permission/upload里面的参数file
        formData.append("file",$scope.showFiles[index].file);
        $.ajax({
            type:"post",
            async:true,  //这里要设置异步上传，才能成功调用myXhr.upload.addEventListener('progress',function(e){}),progress的回掉函数
            Accept:'text/html;charset=UTF-8',
            data:formData,
            //contentType:'multipart/form-data',
            url: '/a_yongan/file/upload/salewarehousing/'+$scope.row.salesOutCkdh,
            processData: false, // 告诉jQuery不要去处理发送的数据
            contentType: false, // 告诉jQuery不要去设置Content-Type请求头
            xhr:function(){
                var myXhr = $.ajaxSettings.xhr();
                if(myXhr.upload){ // check if upload property exists
                    myXhr.upload.addEventListener('progress',function(e){
                        var loaded = e.loaded;                  //已经上传大小情况
                        var total = e.total;                      //附件总大小
                        var percent = Math.floor(100*loaded/total);     //+"%"已经上传的百分比
                        $scope.showFiles[index].progress = percent;
                        //$("#processBar").css("width",percent);
                    }, false); // for handling the progress of the upload
                }
                return myXhr;
            },
            success:function(data){
                if(data.success){
                    showMessage('success','','上传成功！');
                    $scope.showFiles[index].myFileId = data.error;
                    $scope.showFiles[index].progress = 100;
                    $scope.showFiles[index].isUploading = true;
                    $scope.showFiles[index].isSuccess = true;
                }else{
                    showMessage('warning','',data.error);
                    $scope.showFiles[index].isUploading = false;
                    $scope.showFiles[index].isSuccess = false;
                }
            },
            error:function(){
                showMessage('warning','','上传失败！');
                $scope.showFiles[index].isUploading = false;
                $scope.showFiles[index].isError = true;
            }
        });
    }
    inIt();
    $scope.isPrint = false;
    $scope.myPrintShow = function(){
        $scope.isPrint = !$scope.isPrint;
        $scope.warehouseAdd = !$scope.warehouseAdd;
    };
    $scope.myPrint = function(){
        var input = $('#orderPrint');
        input.print({
            globalStyles:true,
            noPrintSelector:'.no-print'
        });
    };

    $scope.showFlowDetailsShow = false;
    $scope.showFlowDetailsData = [];
    $scope.showFlowDetails = function(){
        if($scope.showFlowDetailsShow){
            $scope.showFlowDetailsShow = false;
        }else{
            $scope.showFlowDetailsShow = true;
            toaster.getInfo('/a_yongan/list/processrecording/'+$scope.row.salesOutId,null).then(function(data){
                if(data && data.data && data.data.data){
                    data.data.data.forEach(function(item){
                        item.createTime = $filter("date")(item.createTime, "yyyy-MM-dd HH:mm:ss");
                        if(item.prType==="起草"){
                            item.prFlowToName = "提单";
                            item.prToUser = item.prUser;
                        }
                    })
                    $scope.showFlowDetailsData = data.data.data;
                }
            });
        }
    };
    $scope.showSelectUser = function(name,id){
        var modalInstance = $modal.open({
            templateUrl: 'selectUser.html',
            controller: 'selectUserCtrl',
            size: 'sm',
            resolve: {
                items: function () {
                    return $scope.message;
                }
            }
        });
        modalInstance.result.then(function (selectedItem) {
            $('#'+name+'').val(selectedItem.name);
            $('#'+id+'').val(selectedItem.id);
            showMessage('success','','选择成功！');
            //$scope.selected = selectedItem;
        }, function () {
            $log.info('Modal dismissed at: ' + new Date());
        });
    };
    $scope.excel = function(){
        toaster.tableToExcel('tableToExcel', '下载模板');
    };
    $scope.actions = {
        showListDetails:function(thisDom){
            var id=thisDom.salesOutId;
            var idDom = $("."+id);
            if(idDom && idDom.css("display")==="none"){
                idDom.css("display","");
            }else{
                idDom.css("display","none");
            }
        },
        closeAll:function(){
            $scope.saveDate.forEach(function(item){
                $("."+item.salesOutId).css("display","none");
            });
        },
        openAll:function(){
            $scope.saveDate.forEach(function(item){
                $("."+item.salesOutId).css("display","");
            });
        },
        search:function(){
            var postData={searchZdrId:"",searchStart:"",searchEnd:"",
                searchGys:"",searchJeStart:"",searchJeEnd:"",searchBm:"",
                searchHpmcId:"",searchShck:"",searchOrderBm:""};
            postData.searchZdrId = $("#searchZdrId").val();
            postData.searchStart = new Date($("#searchStart").val()).getTime();
            postData.searchEnd = new Date($("#searchEnd").val()).getTime();
            postData.searchGys = $("#searchGys").val();
            postData.searchJeStart = $("#searchJeStart").val()==""?"0":$("#searchJeStart").val();
            postData.searchJeEnd = $("#searchJeEnd").val()==""?"0":$("#searchJeEnd").val();
            postData.searchBm = $("#searchBm").val();
            postData.searchHpmcId = $("#searchHpmcId").val();
            postData.searchShck = $scope.lists[$("#searchShck").val()];
            postData.searchOrderBm = $("#searchOrderBm").val();
            toaster.postInfo('/a_yongan/selectall/saleWarehousing',postData).then(function(data){
                if(data && data.data && data.data.data){
                    makeData(data.data.data);
                }
            });
        }
    };
}])
;